#!/usr/bin/env python
# encoding=utf-8

import sys

from wechatpy.replies import TextReply, ArticlesReply

from .. import dao
from ..logger import log, WECHAT_MSG_EVENT
from ..models import UserLog

reload(sys)
sys.setdefaultencoding('utf-8')

__author__ = 'xlzd'


def handle_msg(msg):
    if msg.type == 'text':
        return handle_text_msg(msg)
    if msg.type == 'subscribe':
        return TextReply(content=u'感谢关注。', message=msg)
    if msg.type == 'event':
        return TextReply(content=u'报答alpha：您可以在聊天窗口输入您要搜索的关键字，我们会进行全文检索；点击“全部文档摘要”可以快速查看搜索结果。', message=msg)
    return TextReply(content=u'暂不支持这种类型的消息，抱歉。', message=msg)


def handle_text_msg(msg):
    log(UserLog(WECHAT_MSG_EVENT, u'from<%s>,type<text>, content<%s>' % (msg.source, msg.content)))
    content = msg.content
    total, data = dao.select_es(content, count=5)
    if not data:
        return TextReply(content=u'没有找到【%s】相关的公告' % content, message=msg)
    reply = ArticlesReply(message=msg, articles=[])
    if total > 5:
        reply.add_article({
            'title': u'关于『%s』的全部文档摘要(共%s份)' % (content, total),
            'url': u'http://biz.socialcredits.cn/wechat/search/' + content,
            'image': 'http://7xj7uc.com1.z0.glb.clouddn.com/more.png'
        })
    for item in data:
        title = item['title']
        if len(title) > 25:
            title = title[:22] + '...'
        title = u'(%s-%s) %s' % (item['companyShortName'], item['stockCode'], title)
        reply.add_article({
            'title': title,
            # 'description': u'%s' % item['description'],
            'url': u'http://biz.socialcredits.cn/wechat/detail/' + item['id'],
            'image': 'http://7xj7uc.com1.z0.glb.clouddn.com/pdffiles.jpg'
        })
    return reply
